/**
 * WebGPU 优化实现 - 继承标准WebGPU API
 * 开发者调用标准WebGPU接口，底层自动进行命令序列化和批量处理
 * 完全透明，对游戏开发者无感知
 * 通过继承保持原有的GC和native绑定机制
 */

const { WebGPUCommandSerializer } = require('./webgpu-command-serializer.js');
const { CommandType } = require('./webgpu-command-protocol.js');

// 获取全局标准WebGPU对象
const OriginalGPUDevice = globalThis.GPUDevice || class GPUDevice {};
const OriginalGPUBuffer = globalThis.GPUBuffer || class GPUBuffer {};
const OriginalGPUTexture = globalThis.GPUTexture || class GPUTexture {};
const OriginalGPUTextureView = globalThis.GPUTextureView || class GPUTextureView {};
const OriginalGPUSampler = globalThis.GPUSampler || class GPUSampler {};
const OriginalGPUShaderModule = globalThis.GPUShaderModule || class GPUShaderModule {};
const OriginalGPURenderPipeline = globalThis.GPURenderPipeline || class GPURenderPipeline {};
const OriginalGPUComputePipeline = globalThis.GPUComputePipeline || class GPUComputePipeline {};
const OriginalGPUBindGroupLayout = globalThis.GPUBindGroupLayout || class GPUBindGroupLayout {};
const OriginalGPUPipelineLayout = globalThis.GPUPipelineLayout || class GPUPipelineLayout {};
const OriginalGPUBindGroup = globalThis.GPUBindGroup || class GPUBindGroup {};
const OriginalGPUQueue = globalThis.GPUQueue || class GPUQueue {};

class GPUDevice extends OriginalGPUDevice {
    constructor(nativeDevice) {
        super(); // 调用父类构造函数
        this._nativeDevice = nativeDevice;
        this._serializer = new WebGPUCommandSerializer();
        this._resourceMap = new Map();
        this._batchMode = false;
        this._autoFlush = true;
        this._commandThreshold = 100; // 命令数量阈值
    }

      // 销毁设备时清理
    destroy() {
        this._serializer.flush();
        // 调用父类的destroy方法（如果存在）
        if (super.destroy) {
            super.destroy();
        }
    }

    // 标准 WebGPU API: createBuffer
    createBuffer(descriptor) {
        const bufferId = this._serializer.serializeCreateBuffer(descriptor);
        
        const buffer = new GPUBuffer(this, bufferId, descriptor);
        this._resourceMap.set(bufferId, buffer);
        
        this._checkFlush();
        return buffer;
    }

    // 标准 WebGPU API: createTexture
    createTexture(descriptor) {
        const textureId = this._serializer.serializeCreateTexture(descriptor);

        const texture = new GPUTexture(this, textureId, descriptor);
        this._resourceMap.set(textureId, texture);

        this._checkFlush();
        return texture;
    }

    // 标准 WebGPU API: createBindGroupLayout
    createBindGroupLayout(descriptor) {
        const layoutId = this._serializer.serializeCreateBindGroupLayout(descriptor);

        const layout = new GPUBindGroupLayout(this, layoutId, descriptor);
        this._resourceMap.set(layoutId, layout);

        this._checkFlush();
        return layout;
    }

    // 标准 WebGPU API: createBindGroup
    createBindGroup(descriptor) {
        const bindGroupId = this._serializer.serializeCreateBindGroup(descriptor);

        const bindGroup = new GPUBindGroup(this, bindGroupId, descriptor);
        this._resourceMap.set(bindGroupId, bindGroup);

        this._checkFlush();
        return bindGroup;
    }

    // 标准 WebGPU API: createPipelineLayout
    createPipelineLayout(descriptor) {
        const layoutId = this._serializer.serializeCreatePipelineLayout(descriptor);

        const layout = new GPUPipelineLayout(this, layoutId, descriptor);
        this._resourceMap.set(layoutId, layout);

        this._checkFlush();
        return layout;
    }

    // 标准 WebGPU API: createSampler
    createSampler(descriptor = {}) {
        const samplerId = this._serializer.serializeCreateSampler(descriptor);

        const sampler = new GPUSampler(this, samplerId, descriptor);
        this._resourceMap.set(samplerId, sampler);

        this._checkFlush();
        return sampler;
    }

    // 标准 WebGPU API: createComputePipeline
    createComputePipeline(descriptor) {
        const pipelineId = this._serializer.serializeCreateComputePipeline(descriptor);

        const pipeline = new GPUComputePipeline(this, pipelineId, descriptor);
        this._resourceMap.set(pipelineId, pipeline);

        this._checkFlush();
        return pipeline;
    }

    // 标准 WebGPU API: createRenderBundleEncoder
    createRenderBundleEncoder(descriptor) {
        const encoderId = this._serializer.serializeCreateRenderBundleEncoder(descriptor);

        const encoder = new GPURenderBundleEncoder(this, encoderId, descriptor);
        this._resourceMap.set(encoderId, encoder);

        this._checkFlush();
        return encoder;
    }

    // 标准 WebGPU API: createShaderModule
    createShaderModule(descriptor) {
        const moduleId = this._serializer.serializeCreateShaderModule(descriptor);
        
        const module = new GPUShaderModule(this, moduleId, descriptor);
        this._resourceMap.set(moduleId, module);
        
        this._checkFlush();
        return module;
    }

    // 标准 WebGPU API: createRenderPipeline
    createRenderPipeline(descriptor) {
        // 收集着色器ID
        const shaderIds = {
            vertex: descriptor.vertex?.module?._id || 0,
            fragment: descriptor.fragment?.module?._id || 0
        };

        const pipelineId = this._serializer.serializeCreateRenderPipeline(descriptor, shaderIds);
        
        const pipeline = new GPURenderPipeline(this, pipelineId, descriptor);
        this._resourceMap.set(pipelineId, pipeline);
        
        this._checkFlush();
        return pipeline;
    }

    // 标准 WebGPU API: createCommandEncoder
    createCommandEncoder(descriptor = {}) {
        return new GPUCommandEncoder(this);
    }

    // 标准 WebGPU API: queue getter
    get queue() {
        if (!this._queue) {
            this._queue = new GPUQueue(this);
        }
        return this._queue;
    }

    // 内部方法：检查是否需要刷新
    _checkFlush() {
        if (this._autoFlush && this._serializer.offset > this._commandThreshold * 64) {
            this._flush();
        }
    }

    // 内部方法：刷新命令到native
    _flush() {
        return this._serializer.flush();
    }

    // 内部方法：强制刷新
    _forceFlush() {
        return this._flush();
    }
}

class GPUBuffer extends OriginalGPUBuffer {
    constructor(device, id, descriptor) {
        super(); // 调用父类构造函数，保持native绑定
        this._device = device;
        this._id = id;
        this._descriptor = descriptor;
        this._mapped = descriptor.mappedAtCreation || false;
        this._mappedRange = null;
    }

    // 标准 WebGPU API: getMappedRange
    getMappedRange(offset = 0, size) {
        if (!this._mapped) {
            throw new Error('Buffer is not mapped');
        }
        
        const rangeSize = size ?? (this._descriptor.size - offset);
        this._mappedRange = new ArrayBuffer(rangeSize);
        return this._mappedRange;
    }

    // 标准 WebGPU API: unmap
    unmap() {
        if (!this._mapped) return;
        
        // 如果有映射的数据，序列化写入命令
        if (this._mappedRange) {
            this._device._serializer.serializeWriteBuffer(this._id, 0, this._mappedRange);
        }
        
        this._mapped = false;
        this._mappedRange = null;
        this._device._checkFlush();
    }

    // 标准 WebGPU API: destroy
    destroy() {
        const startOffset = this._device._serializer.offset;
        this._device._serializer.writeCommandHeader(CommandType.DESTROY_BUFFER, 0);
        this._device._serializer.writeUint32(this._id);
        
        const commandSize = this._device._serializer.offset - startOffset;
        new DataView(this._device._serializer.buffer).setUint32(startOffset + 4, commandSize, true);
        
        this._device._checkFlush();
    }

    get size() {
        return this._descriptor.size;
    }

    get usage() {
        return this._descriptor.usage;
    }
}

class GPUTexture extends OriginalGPUTexture {
    constructor(device, id, descriptor) {
        super(); // 调用父类构造函数，保持native绑定
        this._device = device;
        this._id = id;
        this._descriptor = descriptor;
    }

    // 标准 WebGPU API: createView
    createView(descriptor = {}) {
        return new GPUTextureView(this._device, this._id, descriptor);
    }

    // 标准 WebGPU API: destroy
    destroy() {
        const startOffset = this._device._serializer.offset;
        this._device._serializer.writeCommandHeader(CommandType.DESTROY_TEXTURE, 0);
        this._device._serializer.writeUint32(this._id);
        
        const commandSize = this._device._serializer.offset - startOffset;
        new DataView(this._device._serializer.buffer).setUint32(startOffset + 4, commandSize, true);
        
        this._device._checkFlush();
    }

    get width() { return this._descriptor.size.width; }
    get height() { return this._descriptor.size.height; }
    get depthOrArrayLayers() { return this._descriptor.size.depthOrArrayLayers || 1; }
    get format() { return this._descriptor.format; }
    get usage() { return this._descriptor.usage; }
}

class GPUTextureView extends OriginalGPUTextureView {
    constructor(device, textureId, descriptor) {
        super(); // 调用父类构造函数，保持native绑定
        this._device = device;
        this._textureId = textureId;
        this._descriptor = descriptor;
        this._id = device._serializer.serializeCreateTextureView(textureId, descriptor);
        device._resourceMap.set(this._id, this);
    }
}

class GPUBindGroupLayout extends OriginalGPUBindGroupLayout {
    constructor(device, id, descriptor) {
        super(); // 调用父类构造函数，保持native绑定
        this._device = device;
        this._id = id;
        this._descriptor = descriptor;
    }
}

class GPUBindGroup extends OriginalGPUBindGroup {
    constructor(device, id, descriptor) {
        super(); // 调用父类构造函数，保持native绑定
        this._device = device;
        this._id = id;
        this._descriptor = descriptor;
    }
}

class GPUPipelineLayout extends OriginalGPUPipelineLayout {
    constructor(device, id, descriptor) {
        super(); // 调用父类构造函数，保持native绑定
        this._device = device;
        this._id = id;
        this._descriptor = descriptor;
        this._refCount = 1;

        // 注册到设备的资源管理器
        this._device._resourceManager.addResource(this._id, this);
    }

    // 增加引用
    addRef() {
        this._refCount++;
        return this;
    }

    // 减少引用，返回true表示可以销毁
    release() {
        this._refCount--;
        if (this._refCount <= 0) {
            this.destroy();
            return true;
        }
        return false;
    }

    // 手动销毁
    destroy() {
        if (this._id !== null) {
            this._device._serializer.serializeDestroyResource(this._id, 'PipelineLayout');
            this._device._resourceManager.removeResource(this._id);
            this._device._checkFlush();
            this._id = null;
        }
    }

    // WebGPU标准接口
    get label() { return this._descriptor.label || ''; }
}

class GPUSampler extends OriginalGPUSampler {
    constructor(device, id, descriptor) {
        super(); // 调用父类构造函数，保持native绑定
        this._device = device;
        this._id = id;
        this._descriptor = descriptor;
    }
}

class GPUComputePipeline extends OriginalGPUComputePipeline {
    constructor(device, id, descriptor) {
        super(); // 调用父类构造函数，保持native绑定
        this._device = device;
        this._id = id;
        this._descriptor = descriptor;
    }
}

class GPURenderBundleEncoder {
    constructor(device, id, descriptor) {
        this._device = device;
        this._id = id;
        this._descriptor = descriptor;
    }

    // 标准 WebGPU API: setPipeline
    setPipeline(pipeline) {
        this._device._serializer.serializeSetPipeline(this._id, pipeline._id);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: setBindGroup
    setBindGroup(index, bindGroup, dynamicOffsets, dynamicOffsetsStart = 0, dynamicOffsetsLength = 0) {
        this._device._serializer.serializeSetBindGroup(this._id, index, bindGroup._id, dynamicOffsets, dynamicOffsetsStart, dynamicOffsetsLength);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: setVertexBuffer
    setVertexBuffer(slot, buffer, offset, size) {
        this._device._serializer.serializeSetVertexBuffer(this._id, slot, buffer._id, offset, size);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: setIndexBuffer
    setIndexBuffer(buffer, format, offset, size) {
        // 将format字符串转换为数字枚举，与Dawn保持一致
        const IndexFormat = {
            'uint16': 0x00000001,          // WGPUIndexFormat_Uint16
            'uint32': 0x00000002           // WGPUIndexFormat_Uint32
        };

        const formatValue = IndexFormat[format] || 0x00000001; // 默认uint16
        this._device._serializer.serializeSetIndexBuffer(this._id, buffer._id, formatValue, offset, size);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: draw
    draw(vertexCount, instanceCount, firstVertex, firstInstance) {
        this._device._serializer.serializeDraw(this._id, vertexCount, instanceCount, firstVertex, firstInstance);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: drawIndexed
    drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance) {
        this._device._serializer.serializeDrawIndexed(this._id, indexCount, instanceCount, firstIndex, baseVertex, firstInstance);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: finish
    finish(descriptor) {
        const bundleId = this._device._serializer.serializeFinishRenderBundleEncoder(this._id, descriptor);
        return new GPURenderBundle(this._device, bundleId);
    }
}

class GPURenderBundle {
    constructor(device, id) {
        this._device = device;
        this._id = id;
    }
}

class GPUShaderModule extends OriginalGPUShaderModule {
    constructor(device, id, descriptor) {
        super(); // 调用父类构造函数，保持native绑定
        this._device = device;
        this._id = id;
        this._descriptor = descriptor;
    }
}

class GPURenderPipeline extends OriginalGPURenderPipeline {
    constructor(device, id, descriptor) {
        super(); // 调用父类构造函数，保持native绑定
        this._device = device;
        this._id = id;
        this._descriptor = descriptor;
    }
}

class GPUCommandEncoder {
    constructor(device) {
        this._device = device;
    }

    // 标准 WebGPU API: beginRenderPass
    beginRenderPass(descriptor) {
        return new GPURenderPassEncoder(this._device, descriptor);
    }

    // 标准 WebGPU API: beginComputePass
    beginComputePass(descriptor = {}) {
        return new GPUComputePassEncoder(this._device, descriptor);
    }

    // 标准 WebGPU API: finish
    finish() {
        const startOffset = this._device._serializer.offset;
        this._device._serializer.writeCommandHeader(CommandType.FINISH_COMMAND_ENCODER, 0);
        
        const commandSize = this._device._serializer.offset - startOffset;
        new DataView(this._device._serializer.buffer).setUint32(startOffset + 4, commandSize, true);
        
        this._device._checkFlush();
        return new GPUCommandBuffer(this._device);
    }
}

class GPUCommandBuffer {
    constructor(device) {
        this._device = device;
    }
}

class GPURenderPassEncoder {
    constructor(device, descriptor) {
        this._device = device;
        
        // 序列化 beginRenderPass 命令
        const startOffset = device._serializer.offset;
        device._serializer.writeCommandHeader(CommandType.BEGIN_RENDER_PASS, 0);
        
        // 序列化render pass descriptor
        this._serializeRenderPassDescriptor(descriptor);
        
        const commandSize = device._serializer.offset - startOffset;
        new DataView(device._serializer.buffer).setUint32(startOffset + 4, commandSize, true);
    }

    _serializeRenderPassDescriptor(descriptor) {
        // 序列化颜色附件
        const colorAttachments = descriptor.colorAttachments || [];
        this._device._serializer.writeUint32(colorAttachments.length);
        
        colorAttachments.forEach(attachment => {
            if (attachment) {
                this._device._serializer.writeUint8(1); // hasAttachment
                this._device._serializer.writeUint32(attachment.view._textureId || 0);
                // 序列化其他属性...
            } else {
                this._device._serializer.writeUint8(0); // noAttachment
            }
        });

        // 序列化深度模板附件
        if (descriptor.depthStencilAttachment) {
            this._device._serializer.writeUint8(1);
            this._device._serializer.writeUint32(descriptor.depthStencilAttachment.view._textureId || 0);
            // 序列化其他深度模板属性...
        } else {
            this._device._serializer.writeUint8(0);
        }
    }

    // 标准 WebGPU API: setPipeline
    setPipeline(pipeline) {
        this._device._serializer.serializeSetPipeline(this._id, pipeline._id);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: setVertexBuffer
    setVertexBuffer(slot, buffer, offset = 0, size) {
        this._device._serializer.serializeSetVertexBuffer(this._id, slot, buffer._id, offset, size || buffer.size);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: setIndexBuffer
    setIndexBuffer(buffer, format, offset = 0, size) {
        this._device._serializer.serializeSetIndexBuffer(this._id, buffer._id, format, offset, size || buffer.size);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: draw
    draw(vertexCount, instanceCount = 1, firstVertex = 0, firstInstance = 0) {
        this._device._serializer.serializeDraw(this._id, vertexCount, instanceCount, firstVertex, firstInstance);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: drawIndexed
    drawIndexed(indexCount, instanceCount = 1, firstIndex = 0, baseVertex = 0, firstInstance = 0) {
        this._device._serializer.serializeDrawIndexed(this._id, indexCount, instanceCount, firstIndex, baseVertex, firstInstance);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: setBindGroup
    setBindGroup(index, bindGroup, dynamicOffsets, dynamicOffsetsStart = 0, dynamicOffsetsLength = 0) {
        this._device._serializer.serializeSetBindGroup(this._id, index, bindGroup._id, dynamicOffsets, dynamicOffsetsStart, dynamicOffsetsLength);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: executeBundles
    executeBundles(renderBundles) {
        const bundleIds = renderBundles.map(bundle => bundle._id);
        this._device._serializer.serializeExecuteBundles(this._id, bundleIds);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: setViewport
    setViewport(x, y, width, height, minDepth, maxDepth) {
        this._device._serializer.serializeSetViewport(this._id, x, y, width, height, minDepth, maxDepth);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: setScissorRect
    setScissorRect(x, y, width, height) {
        this._device._serializer.serializeSetScissorRect(this._id, x, y, width, height);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: setBlendConstant
    setBlendConstant(color) {
        this._device._serializer.serializeSetBlendConstant(this._id, color);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: setStencilReference
    setStencilReference(reference) {
        this._device._serializer.serializeSetStencilReference(this._id, reference);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: end
    end() {
        this._device._serializer.serializeEndRenderPass(this._id);
        this._device._checkFlush();
    }
}

class GPUComputePassEncoder {
    constructor(device, descriptor) {
        this._device = device;
        device._serializer.serializeBeginComputePass(descriptor);
    }

    // 标准 WebGPU API: dispatchWorkgroups
    dispatchWorkgroups(workgroupCountX, workgroupCountY = 1, workgroupCountZ = 1) {
        this._device._serializer.serializeDispatch(workgroupCountX, workgroupCountY, workgroupCountZ);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: end
    end() {
        this._device._serializer.serializeEndComputePass();
        this._device._checkFlush();
    }
}

class GPUQueue extends OriginalGPUQueue {
    constructor(device) {
        super(); // 调用父类构造函数，保持native绑定
        this._device = device;
    }

    // 标准 WebGPU API: writeBuffer
    writeBuffer(buffer, bufferOffset, data, dataOffset = 0, size) {
        const actualData = size ? data.slice(dataOffset, dataOffset + size) : data.slice(dataOffset);
        this._device._serializer.serializeWriteBuffer(buffer._id, bufferOffset, actualData);
        this._device._checkFlush();
    }

    // 标准 WebGPU API: submit
    submit(commandBuffers) {
        const startOffset = this._device._serializer.offset;
        this._device._serializer.writeCommandHeader(CommandType.SUBMIT, 0);
        this._device._serializer.writeUint32(commandBuffers.length);
        
        // 命令缓冲区已经序列化完成，这里只需要提交
        const commandSize = this._device._serializer.offset - startOffset;
        new DataView(this._device._serializer.buffer).setUint32(startOffset + 4, commandSize, true);
        
        // 提交时强制刷新所有命令
        this._device._forceFlush();
    }
}

// 替换全局WebGPU实现
function installWebGPU() {
    if (!globalThis.navigator) {
        globalThis.navigator = {};
    }

    if (!globalThis.navigator.gpu) {
        globalThis.navigator.gpu = {
            requestAdapter: async (options) => {
                return new GPUAdapter();
            }
        };
    }
}

class GPUAdapter {
    async requestDevice(descriptor = {}) {
        // 这里可以调用原生的adapter来获取能力信息
        return new GPUDevice();
    }
}

// 导出模块
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        installWebGPU,
        GPUDevice,
        GPUBuffer,
        GPUTexture,
        GPUTextureView,
        GPUBindGroup,
        GPUBindGroupLayout,
        GPUPipelineLayout,
        GPUSampler,
        GPUShaderModule,
        GPURenderPipeline,
        GPUComputePipeline,
        GPUQueue,
        GPUAdapter
    };
}

// 自动安装版本
installWebGPU();